<template>
  <div class="login-container">
    <!-- 背景图片轮播 -->
    <div class="background-carousel">
      <div
        v-for="(image, index) in backgroundImages"
        :key="index"
        class="background-slide"
        :class="{ active: currentImageIndex === index }"
        :style="{ backgroundImage: `url(${image})` }"
      ></div>
    </div>

    <!-- 渐变遮罩层 -->
    <div class="background-overlay"></div>

    <div class="login-background">
      <div class="login-content">
        <div class="login-header">
          <div class="logo-section">
            <div class="logo-container">
              <img src="@/assets/logo.png" alt="中山大学logo" class="logo-image" />
            </div>

            <p>校企对接平台</p>
          </div>
        </div>

        <div class="login-card-container">
          <el-card class="login-card" shadow="never">
            <template #header>
              <div class="card-header">
                <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
                <p>{{ isLogin ? '欢迎使用校企对接平台' : '创建您的账户' }}</p>
              </div>
            </template>

            <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-width="80px"
              size="large"
              @keyup.enter="handleSubmit"
            >
              <el-form-item :label="isLogin ? '邮箱' : '用户名'" prop="username">
                <el-input
                  v-model="form.username"
                  :placeholder="isLogin ? '请输入邮箱地址' : '请输入用户名'"
                  prefix-icon="User"
                  clearable
                />
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="form.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  show-password
                  clearable
                />
              </el-form-item>

              <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="form.confirmPassword"
                  type="password"
                  placeholder="请再次输入密码"
                  prefix-icon="Lock"
                  show-password
                  clearable
                />
              </el-form-item>

              <el-form-item label="用户角色" prop="role">
                <el-select v-model="form.role" placeholder="请选择用户角色" style="width: 100%">
                  <el-option label="企业用户" value="enterprise">
                    <div class="role-option">
                      <el-icon color="#2e7d32"><OfficeBuilding /></el-icon>
                      <span>企业用户</span>
                      <small>发布课题、管理项目</small>
                    </div>
                  </el-option>
                  <el-option label="导师用户" value="tutor">
                    <div class="role-option">
                      <el-icon color="#4caf50"><User /></el-icon>
                      <span>导师用户</span>
                      <small>申请课题、指导学生</small>
                    </div>
                  </el-option>
                  <el-option label="学生用户" value="student">
                    <div class="role-option">
                      <el-icon color="#66bb6a"><User /></el-icon>
                      <span>学生用户</span>
                      <small>申请课题、参与研究</small>
                    </div>
                  </el-option>
                  <el-option label="管理员" value="admin">
                    <div class="role-option">
                      <el-icon color="#ff9800"><Setting /></el-icon>
                      <span>管理员</span>
                      <small>系统管理、数据统计</small>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item v-if="!isLogin" label="真实姓名" prop="realName">
                <el-input
                  v-model="form.realName"
                  placeholder="请输入真实姓名"
                  prefix-icon="User"
                  clearable
                />
              </el-form-item>

              <el-form-item v-if="!isLogin" label="邮箱" prop="email">
                <el-input
                  v-model="form.email"
                  placeholder="请输入邮箱地址"
                  prefix-icon="Message"
                  clearable
                />
              </el-form-item>

              <el-form-item v-if="!isLogin" label="手机号" prop="phone">
                <el-input
                  v-model="form.phone"
                  placeholder="请输入手机号码"
                  prefix-icon="Phone"
                  clearable
                />
              </el-form-item>

              <el-form-item v-if="isLogin">
                <div class="login-options">
                  <el-checkbox v-model="form.rememberMe">记住密码</el-checkbox>
                  <el-button type="text" @click="forgotPassword">忘记密码？</el-button>
                </div>
              </el-form-item>
            </el-form>

            <div class="button-container">
              <el-button
                type="primary"
                :loading="loading"
                @click="handleSubmit"
                class="submit-button"
              >
                {{ isLogin ? '登录' : '注册' }}
              </el-button>
            </div>

            <div class="form-footer">
              <span>{{ isLogin ? '还没有账户？' : '已有账户？' }}</span>
              <el-button type="text" @click="toggleMode">
                {{ isLogin ? '立即注册' : '立即登录' }}
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { School, User, OfficeBuilding, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 导入背景图片
import banner1 from '@/assets/banner1-Vjwxq.jpg'
import banner3 from '@/assets/banner3-1mewp.jpg'
import banner4 from '@/assets/banner4-1PVrZ.jpg'
import banner5 from '@/assets/banner5-Zs5PL.jpg'
import banner6 from '@/assets/banner6-8RupQ.jpg'
import banner7 from '@/assets/banner7-4nOz3.jpg'

const router = useRouter()
const userStore = useAuthStore()

const isLogin = ref(true)
const loading = ref(false)
const formRef = ref()

// 背景轮播相关
const backgroundImages = [banner1, banner3, banner4, banner5, banner6, banner7]
const currentImageIndex = ref(0)
let carouselTimer: number | null = null

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  role: '',
  realName: '',
  email: '',
  phone: '',
  rememberMe: false,
})

const rules = computed(() => {
  const baseRules = {
    username: isLogin.value ? [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    ] : [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    ],
    role: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  }

  if (!isLogin.value) {
    return {
      ...baseRules,
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule: any, value: string, callback: Function) => {
            if (value !== form.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur',
        },
      ],
      realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
      ],
    }
  }

  return baseRules
})

const toggleMode = () => {
  isLogin.value = !isLogin.value
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isLogin.value) {
      // 登录逻辑
      const result = await userStore.login(form.username, form.password)
      if (result.success) {
        ElMessage.success('登录成功！')

        // 根据角色跳转到不同页面
        const roleRoutes: Record<string, string> = {
          enterprise: '/enterprise',
          tutor: '/mentor',
          student: '/student',
          admin: '/admin',
        }

        const targetRoute = roleRoutes[userStore.userInfo?.role || ''] || '/'
        router.push(targetRoute)
      } else {
        ElMessage.error('登录失败')
      }
    } else {
      // 注册逻辑
      const result = await userStore.register({
        username: form.username,
        email: form.email,
        password: form.password,
        role: form.role,
        phone: form.phone,
        real_name: form.realName,
      })
      if (result.success) {
        isLogin.value = true
        formRef.value.resetFields()
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

const forgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}

// 背景轮播逻辑
const startCarousel = () => {
  carouselTimer = window.setInterval(() => {
    currentImageIndex.value = (currentImageIndex.value + 1) % backgroundImages.length
  }, 4000) // 每4秒切换一次
}

const stopCarousel = () => {
  if (carouselTimer) {
    window.clearInterval(carouselTimer)
    carouselTimer = null
  }
}

// 生命周期
onMounted(() => {
  startCarousel()
})

onUnmounted(() => {
  stopCarousel()
})
</script>

<style scoped>
/* 主容器 */
.login-container {
  position: relative;
  min-height: 100vh;
  overflow: hidden;
}

/* 背景轮播 */
.background-carousel {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.background-slide {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  opacity: 0;
  transition: opacity 1.5s ease-in-out;
  transform: scale(1.1);
}

.background-slide.active {
  opacity: 1;
}

/* 渐变遮罩层 */
.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.3) 0%,
    rgba(46, 125, 50, 0.2) 50%,
    rgba(0, 0, 0, 0.4) 100%
  );
  z-index: 2;
}

.login-background {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  z-index: 3;
}

.login-content {
  width: 100%;
  max-width: 1200px;
  display: flex;
  align-items: center;
  gap: 80px;
  animation: fadeInUp 0.8s ease-out;
}

/* Logo部分 */
.login-header {
  flex: 1;
  text-align: center;
  color: white;
}

.logo-container {
  margin-bottom: 24px;
}

.logo-image {
  width: 550px;
  object-fit: contain;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));
}

.logo-section p {
  font-size: 48px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  font-weight: 500;
}

/* 登录卡片容器 */
.login-card-container {
  flex: 1;
  max-width: 480px;
  animation: slideInRight 0.8s ease-out 0.2s both;
}

/* 毛玻璃效果登录卡片 */
.login-card {
  background: rgba(255, 255, 255, 0.1);
  /* backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px); */
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 24px;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.1),
    0 4px 16px rgba(0, 0, 0, 0.05),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.login-card:hover {
  transform: translateY(-4px);
  box-shadow:
    0 16px 48px rgba(0, 0, 0, 0.15),
    0 8px 24px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
}

/* 卡片头部 */
.card-header {
  text-align: center;
  padding: 8px 0;
}

.card-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: white;
  margin: 0 0 8px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.card-header p {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-weight: 300;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9) !important;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.2);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
  background: rgba(255, 255, 255, 0.25);
}

:deep(.el-input__inner) {
  color: white;
  font-weight: 400;
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.el-select .el-input .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.15);
}

/* 角色选择选项 */
.role-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

.role-option span {
  font-weight: 500;
  color: #333;
}

.role-option small {
  color: #666;
  font-size: 12px;
}

/* 登录选项 */
.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-checkbox__label) {
  color: rgba(255, 255, 255, 0.9) !important;
}

:deep(.el-button--text) {
  color: rgba(255, 255, 255, 0.8) !important;
}

:deep(.el-button--text:hover) {
  color: white !important;
}

/* 按钮容器 - 居中 */
.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}

/* 提交按钮样式 */
.submit-button {
  width: 80%;
  height: 52px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 16px;
  border: none;
  background: linear-gradient(
    135deg,
    #66bb6a 0%,
    #4caf50 25%,
    #43a047 50%,
    #388e3c 75%,
    #2e7d32 100%
  );
  color: white;
  box-shadow:
    0 4px 16px rgba(76, 175, 80, 0.3),
    0 2px 8px rgba(46, 125, 50, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.submit-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.6s ease;
}

.submit-button:hover {
  transform: translateY(-3px);
  box-shadow:
    0 8px 32px rgba(76, 175, 80, 0.4),
    0 4px 16px rgba(46, 125, 50, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
  background: linear-gradient(
    135deg,
    #81c784 0%,
    #66bb6a 25%,
    #4caf50 50%,
    #43a047 75%,
    #388e3c 100%
  );
}

.submit-button:hover::before {
  left: 100%;
}

.submit-button:active {
  transform: translateY(-1px);
  box-shadow:
    0 4px 16px rgba(76, 175, 80, 0.3),
    0 2px 8px rgba(46, 125, 50, 0.2);
}

/* 兼容性：保持原有按钮样式作为后备 */
:deep(.el-button--primary) {
  height: 52px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 16px;
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(76, 175, 80, 0.3);
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(76, 175, 80, 0.4);
}

/* 表单底部 */
.form-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.form-footer .el-button--text) {
  color: skyblue !important;
  font-weight: 600;
}

/* 动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(50px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .login-content {
    gap: 40px;
  }

  .logo-section h1 {
    font-size: 32px;
  }

  .logo-section p {
    font-size: 18px;
  }
}

@media (max-width: 768px) {
  .login-content {
    flex-direction: column;
    gap: 30px;
    max-width: 100%;
  }

  .login-header {
    order: 1;
  }

  .login-card-container {
    order: 2;
    max-width: 100%;
    width: 100%;
  }

  .logo-image {
    width: 60px;
    height: 60px;
  }

  .logo-section h1 {
    font-size: 28px;
  }

  .logo-section p {
    font-size: 16px;
  }

  .card-header h2 {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .login-background {
    padding: 12px;
  }

  .logo-section h1 {
    font-size: 24px;
  }

  .logo-section p {
    font-size: 14px;
  }
}
</style>
